package com.ljw.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ljw.gulimall.product.service.CategoryBrandRelationService;
import com.ljw.gulimall.product.vo.Catelog2Vo;
import org.apache.commons.lang3.StringUtils;
//import org.redisson.api.RLock;
//import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljw.common.utils.PageUtils;
import com.ljw.common.utils.Query;

import com.ljw.gulimall.product.dao.CategoryDao;
import com.ljw.gulimall.product.entity.CategoryEntity;
import com.ljw.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

//    @Autowired
//    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);

        List<CategoryEntity> collect = entities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map(categoryEntity -> {
            categoryEntity.setChildren(this.findChildren(categoryEntity, entities));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1、检查当前当前菜单是否被其它地方引用
         baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] getCatelogPath(Long catelogId) {
        List<Long> path = new ArrayList<>();
        this.getNodeParentId(catelogId, path);
        Collections.reverse(path);
        Long[] catelogPath = path.toArray(new Long[path.size()]);
        return catelogPath;
    }

    /**
     * 级联更新所有关联数据
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        //1、更新自己的数据
        baseMapper.updateById(category);
        //2、更新关联的数据
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    /**
     * 查询出所有的一级分类
     * @return
     */
    @Override
    @Cacheable(value = {"category"}, key = "#root.method.name")
    public List<CategoryEntity> getLevel1Categorys() {
        LambdaQueryWrapper<CategoryEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CategoryEntity::getParentCid, 0);
        List<CategoryEntity> entities = baseMapper.selectList(wrapper);
        return entities;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isEmpty(catalogJson)){
//            Map<String, List<Catelog2Vo>> catalogJsonFromDB = this.getCatalogJsonFromDBWithRedissonLock();
            Map<String, List<Catelog2Vo>> catalogJsonFromDB = this.getCatalogJsonFromDB();
            String jsonString = JSON.toJSONString(catalogJsonFromDB);
            redisTemplate.opsForValue().set("catalogJson", jsonString);
            return catalogJsonFromDB;
        }
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }

//    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithRedissonLock() {
//        RLock lock = redisson.getLock("catelogJson-lock");
//        lock.lock();
//        Map<String, List<Catelog2Vo>> dataFromDb;
//        try {
//            dataFromDb = this.getCatalogJsonFromDB();
//        }finally {
//            lock.unlock();
//        }
//        return dataFromDb;
//    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDB() {
        List<CategoryEntity> all = baseMapper.selectList(new LambdaQueryWrapper<>());
        List<CategoryEntity> level1Categorys = all.stream().filter( categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).collect(Collectors.toList());
        Map<String, List<Catelog2Vo>> collect = level1Categorys.stream().collect(Collectors.toMap(categoryEntity -> {
            return categoryEntity.getCatId().toString();
        }, categoryEntity -> {
            List<CategoryEntity> categoryEntities = this.getParentCategoryList(all, categoryEntity.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(categoryEntity.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    List<CategoryEntity> categoryEntities1 = this.getParentCategoryList(all, l2.getCatId());
                    List<Catelog2Vo.Catelog3Vo> catelog3Vos = null;
                    if (categoryEntities1 != null) {
                        catelog3Vos = categoryEntities1.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                    }
                    catelog2Vo.setCatalog3List(catelog3Vos);
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return collect;
    }

    private List<CategoryEntity> getParentCategoryList(List<CategoryEntity> all, Long parentId){
        List<CategoryEntity> collect = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == parentId;
        }).collect(Collectors.toList());
        return collect;
    }

    private void getNodeParentId(Long catelogId, List<Long> path){
        path.add(catelogId);
        CategoryEntity categoryEntity = baseMapper.selectById(catelogId);
        if (categoryEntity.getParentCid() != 0){
            this.getNodeParentId(categoryEntity.getParentCid(), path);
        }
    }

    private List<CategoryEntity> findChildren(CategoryEntity nowCategoryEntity, List<CategoryEntity> all){
        List<CategoryEntity> collect = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(nowCategoryEntity.getCatId());
        }).map(categoryEntity -> {
            categoryEntity.setChildren(this.findChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

}